package com.example.demo.Activity;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;

import com.blankj.utilcode.util.ThreadUtils;
import com.example.demo.Bean.Currency;
import com.example.demo.Bean.CurrencyState;
import com.example.demo.Bean.Userdata;
import com.example.demo.KlineChart.DataHelper;
import com.example.demo.KlineChart.KLineMenuView;
import com.example.demo.R;
import com.example.demo.Service.SaleService;
import com.github.fujianlian.klinechart.KLineChartAdapter;
import com.github.fujianlian.klinechart.KLineChartView;
import com.github.fujianlian.klinechart.KLineEntity;
import com.github.fujianlian.klinechart.formatter.DateFormatter;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class KlineChartActivity extends AppCompatActivity implements View.OnClickListener{

    private TextView tvClose;
    private TextView tvRatio;
    private TextView tvHigh;
    private TextView tvLow;
    private TextView tv24hour;
    private TextView userCount; //用户持币数量
    private List<Userdata> userData = new ArrayList<Userdata>();
    private Button buyButton, sellButton;
    private KLineMenuView tabKline;
    private KLineChartView kLineChartView;
    private DataHelper mDataHelper = new DataHelper();
    private SaleService.SaleBinder saleBinder;  //交易服务绑定器
    public Intent bindIntent;   //服务跳转

    private List<String> tabTitles = Arrays.asList("1分", "5分", "15分", "30分", "1时", "1天");

    private List<String> tabParams = Arrays.asList("1min", "5min", "15min", "30min", "60min", "1day");

    private String coinCode;

    private int defaultIndex = 0;

    private KLineChartAdapter adapter;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            saleBinder = (SaleService.SaleBinder) service;
            if(bindIntent.getStringExtra("Method").equals("buy"))
                if(saleBinder.buy()) {
                    Toast.makeText(KlineChartActivity.this,"交易成功！",Toast.LENGTH_LONG).show();
                    initData();
                    loadData();
                }
                else Toast.makeText(KlineChartActivity.this,"余额不足，交易失败！",Toast.LENGTH_LONG).show();
            if(bindIntent.getStringExtra("Method").equals("sell"))
                if(saleBinder.sell()) {
                    Toast.makeText(KlineChartActivity.this,"交易成功！",Toast.LENGTH_LONG).show();
                    initData();
                    loadData();
                }
                else Toast.makeText(KlineChartActivity.this,"余额不足，交易失败！",Toast.LENGTH_LONG).show();
            unbindService(connection);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {}
    };

    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.buy_currency:
                showInputDialog(0);
                break;
            case R.id.sell_currency:
                showInputDialog(1);
                break;
            default:
                break;
        }
    }

    public void showInputDialog(int state) {
        EditText editText = new EditText(this);
        String str = "";
        String message = "";
        double can = 0;
        DecimalFormat decimalFormat =new DecimalFormat("0.0000");
        if(state == 0){
            str = "请输入买币的数量";
            for(int i = 0; i < userData.size(); i++) {
                if(userData.get(i).getId().equals("###")) {
                    can = Double.parseDouble(userData.get(i).getCount()) / Float.parseFloat(mDataHelper.getClose());
                    message = "最大可买入数量：" + decimalFormat.format(can);
                    break;
                }
            }
        }
        else{
            str = "请输入卖币的数量";
            for(int i = 0; i < userData.size(); i++) {
                if(userData.get(i).getId().equals(getIntent().getStringExtra("currencyName"))) {
                    can = Double.parseDouble(userData.get(i).getCount());
                    message = "最大可以卖出数量：" + decimalFormat.format(can);
                    break;
                }
            }
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(str)
                .setView(editText)
                .setMessage(message)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String count = editText.getText().toString();
                        if(isNumeric(count)) {
                            bindIntent = new Intent(KlineChartActivity.this, SaleService.class);
                            bindIntent.putExtra("nowPrice",mDataHelper.getClose());
                            bindIntent.putExtra("currencyName", getIntent().getStringExtra("currencyName"));
                            bindIntent.putExtra("currencyNum", count);
                            bindIntent.putExtra("userData",(Serializable)userData);
                            if(state == 0) bindIntent.putExtra("Method","buy");
                            else bindIntent.putExtra("Method","sell");
                            bindService(bindIntent, connection, BIND_AUTO_CREATE);
                        }
                        else Toast.makeText(KlineChartActivity.this,"请输入正确的数字！",Toast.LENGTH_SHORT).show();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
        builder.show();
    }

    private boolean isNumeric(String str) {
        double num;
        try{
            num = Double.parseDouble(str);
        }catch (Exception e){
            return false;
        }
        if(num <= 0) return false;
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kline_chart);
        moveStatusbar();
        initview();
        initData();
        coinCode = tabParams.get(defaultIndex);
        tabKline.setData(tabTitles);
        tabKline.setOnTabSelectListener(new KLineMenuView.OnTabSelectListener() {
            @Override
            public void onTabClick(int position) {
                defaultIndex = position;
                loadData();
            }
        });
        initKLineView();
        Toolbar mToolbarTb = (Toolbar) findViewById(R.id.kline_toolbar);
        setSupportActionBar(mToolbarTb);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbarTb.setTitle(getIntent().getStringExtra("currencyName") + "/USDT");
        //setTrend();
    }

    private void moveStatusbar() {
        if(Build.VERSION.SDK_INT >= 21) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(this.getResources().getColor(R.color.color_141D32));
            window.setNavigationBarColor(this.getResources().getColor(R.color.color_141D32));
        }
    }

    private void initview() {
        tvClose = (TextView) findViewById(R.id.tv_close);
        tvRatio = (TextView) findViewById(R.id.tv_ratio);
        tvHigh = (TextView) findViewById(R.id.tv_high);
        tvLow = (TextView) findViewById(R.id.tv_low);
        tv24hour = (TextView) findViewById(R.id.tv_24hour);
        userCount = (TextView) findViewById(R.id.now_count);
        tabKline = (KLineMenuView) findViewById(R.id.tab_kline);
        kLineChartView = (KLineChartView) findViewById(R.id.kLineChartView);
        buyButton = (Button) findViewById(R.id.buy_currency);
        sellButton = (Button) findViewById(R.id.sell_currency);
        buyButton.setOnClickListener(this);
        sellButton.setOnClickListener(this);
    }

    void initData() {
        if(userData.size() != 0) userData.clear();
        BmobQuery<Userdata> userdataBmobQueryBmobQuery = new BmobQuery<>();
        userdataBmobQueryBmobQuery.addWhereEqualTo("username", BmobUser.getCurrentUser().getUsername());
        userdataBmobQueryBmobQuery.order("-id");
        userdataBmobQueryBmobQuery.findObjects(new FindListener<Userdata>() {
            @Override
            public void done(List<Userdata> mlist, BmobException e) {
                if (e == null) {
                    userData = mlist;
                }
            }
        });
    }

    private void initKLineView() {
        adapter = new KLineChartAdapter();
        kLineChartView.setAdapter(adapter);
        kLineChartView.setDateTimeFormatter(new DateFormatter());
        kLineChartView.setGridRows(4);
        kLineChartView.setGridColumns(4);
        kLineChartView.setSelectedYLineColor(getResources().getColor(R.color.chart_sel_y_color));
        kLineChartView.setSelectedYLineWidth(getResources().getDimension(R.dimen.dp_6));
    }

    private void loadData() {
        kLineChartView.justShowLoading();
        ThreadUtils.executeByCached(new ThreadUtils.Task<List<KLineEntity>>() {
            @Nullable
            @Override
            public List<KLineEntity> doInBackground() throws Throwable {
                return mDataHelper.initData(tabParams.get(defaultIndex), getIntent().getStringExtra("currencyName"));
            }

            @Override
            public void onSuccess(@Nullable List<KLineEntity> result) {
                setData(result);
            }

            @Override
            public void onCancel() {
                kLineChartView.hideLoading();
            }

            @Override
            public void onFail(Throwable t) {
                kLineChartView.hideLoading();
            }
        });
    }

    private void setData(List<KLineEntity> kLineList) {
        if (adapter.getCount() == 0) {
            kLineChartView.startAnimation();
        }
        adapter.replaceData(kLineList);
        kLineChartView.refreshEnd();

        if(mDataHelper.getRatio().contains("-")) {
            tvClose.setTextColor(this.getResources().getColor(R.color.chart_green));
            tvRatio.setTextColor(this.getResources().getColor(R.color.chart_green));
        } //跌的时候改为红色
        tvClose.setText(mDataHelper.getClose());
        tvRatio.setText(mDataHelper.getRatio());
        tvHigh.setText(mDataHelper.getHighest());
        tvLow.setText(mDataHelper.getLowest());
        tv24hour.setText(mDataHelper.get24hour());
        while(userData.size() == 0);
        for(int i = 0; i < userData.size() - 1; i++) {
            if(userData.get(i).getId().equals(getIntent().getStringExtra("currencyName"))) {
                DecimalFormat decimalFormat =new DecimalFormat("0.00");
                userCount.setText(decimalFormat.format(Float.parseFloat(userData.get(i).getCount())));
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break; //实现返回
            default: break;
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
        loadData();
    }

    private void setTrend() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initData();
                            loadData();
                        }
                    });
                }
            }
        }).start();
    }

}
